package it.example.pad.mouseComponent;

import it.example.pad.Driver;
import it.example.pad.RectEdges;
import android.util.Log;
import android.view.MotionEvent;

public class Pad implements MouseComponent {

	private static final int INVALID_ID = -1;
	private int x,y,width,height;
	private int id= INVALID_ID;
	private float currentX, currentY;
	private Driver driver;


	public Pad(RectEdges edges) {
		super();
		this.x = edges.getLeft();
		this.y = edges.getTop();
		this.width = edges.getRigth()-x;
		this.height = edges.getBottom()-y;
		driver = Driver.getDriver();
	}

	public void receiveEvent(MotionEvent event) {
		if(event.getAction() == MotionEvent.ACTION_DOWN){
			if(isInPad(event.getX(), event.getY())){
				currentX=event.getX(0);
				currentY=event.getY(0);
				id = event.getPointerId(0);
				Log.d("AAAA","Pad");
			}
		}
		else if(event.getAction() == MotionEvent.ACTION_MOVE){
			int index = event.findPointerIndex(id);
			if(index >= 0 && isInPad(event.getX(index), event.getY(index)))
			{
				int dx,dy;
				dx=(int)(event.getX(index)-currentX);
				dy=(int)(event.getY(index)-currentY);
				currentX=event.getX(index);
				currentY=event.getY(index);
				driver.sendMove(dx,dy);
			}
		}
		else if((event.getAction() & MotionEvent.ACTION_MASK)==MotionEvent.ACTION_POINTER_DOWN){
			int index = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
			if(isInPad(event.getX(index), event.getY(index))){
				currentX=event.getX(index);
				currentY=event.getY(index);
				id = event.getPointerId(index);
				Log.d("AAAA", "id = "+id);
			}
		}else if((event.getAction() & MotionEvent.ACTION_MASK)==MotionEvent.ACTION_POINTER_UP){
			int index = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
			if(event.getPointerId(index)==id)
				id = INVALID_ID;
		}else if(event.getAction() == MotionEvent.ACTION_UP)
			id = INVALID_ID;
	}
	private boolean isInPad(float x, float y) {
		if(x>=this.x && x <=this.x+width && y>=this.y && y <=this.y+height)
			return true;
		else
			return false;
	}
}